package com.zerowidth.moc.web.pay.ls;

import com.mysql.cj.log.Log;
import com.zerowidth.db.op.LogDB;
import com.zerowidth.moc.web.utils.GsonUtils;
import com.zerowidth.moc.web.utils.IOUtil;
import com.zerowidth.moc.web.utils.LogUtil;
import com.zerowidth.moc.web.utils.StringUtils;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

public class LSPayOrderFactory {

    private static final String TAG = "LSPayOrderFactory";

    private static final String URL = "https://api.lspay.tech";

    private static String MY_SERVER_IP = "116.62.121.194";

    private static String SECRET = "yOJr8MgAaiyzjIbwC1VItS2IiZ5FDmHBnsnpxe7nad5JH52RjTXul8j0FrjOxHS4BYCMafwDn5zesjsVJ9glnXvxUJsKBbafJo8gJ8T8FSFwKrIyORoOb4bOjHtJ0zyS";


    /**
     * @param payType
     * @param subject
     * @param outTradeNo
     * @param notifyUrl
     * @param amount     支付金额，单位：分
     */
    public static LSOrderBean createOrderInfo(int payType, String subject, String body, String outTradeNo,
                                              String notifyUrl, int amount) {

        Map<String, String> params = new TreeMap<>();
        params.put("mch_no", "1709521047");
        params.put("app_id", "2496354505743400960");
        params.put("mch_order_no", outTradeNo);
        params.put("way_code", "WX_LITE_H5");
        params.put("amount", String.valueOf(amount));
        params.put("currency", "cny");
        params.put("client_ip", MY_SERVER_IP);
        params.put("subject", subject);
        params.put("body", body);
        params.put("notify_url", notifyUrl);
        params.put("return_url", "");
        params.put("req_time", System.currentTimeMillis() + "");
        params.put("version", "1.0");
        params.put("sign_type", "MD5");
        params.put("sign", generateSignature(params, SECRET));

        LogUtil.e("params = " + params);


        FormBody.Builder form = new FormBody.Builder();
        Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            form.add(entry.getKey(), entry.getValue());
        }

        FormBody formBody = form.build();

        Request request = new Request.Builder()
                .url(URL + "/gateway/unifiedorder")
                .post(formBody)
                .build();
        Response response = null;

        try {
            response = getOkHttpClient().newCall(request).execute();

            String back = response.body().string();

            LogUtil.e(TAG, back);

            if (GsonUtils.getIntFromJson(back, "status") == 200) {
                LSOrderBean bean = GsonUtils.fromJsonStr(back, LSOrderBean.class);
                LogUtil.e(TAG, "pay_info = " + bean.data.pay_info);
                return bean;
            } else {
                LSOrderBean bean = new LSOrderBean();
                bean.msg = GsonUtils.getStringFromJson(back, "msg");
                return bean;
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtil.close(response);
        }

        return null;
    }

    private static OkHttpClient getOkHttpClient() {
        OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();

        long timeOut = 20_000;

        okHttpClientBuilder.callTimeout(timeOut, TimeUnit.MILLISECONDS);
        okHttpClientBuilder.connectTimeout(timeOut, TimeUnit.MILLISECONDS);
        okHttpClientBuilder.writeTimeout(timeOut, TimeUnit.MILLISECONDS);
        okHttpClientBuilder.readTimeout(timeOut, TimeUnit.MILLISECONDS);

        return okHttpClientBuilder.build();
    }

    /**
     * 生成签名
     */
    private static String generateSignature(Map<String, String> data, String secret) {
        try {
            // 将数据按照键名进行排序
            Map<String, String> sortedData = new TreeMap<>(data);

            // 构建待签名字符串
            StringBuilder stringBuilder = new StringBuilder();
            for (Map.Entry<String, String> entry : sortedData.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                if (value != null && !value.isEmpty()) {
                    stringBuilder.append(key).append("=").append(value).append("&");
                }
            }
            stringBuilder.append("key=").append(secret);

            // 计算 MD5 签名
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(stringBuilder.toString().getBytes());
            byte[] digest = md5.digest();

            // 将字节数组转换为十六进制字符串
            StringBuilder signature = new StringBuilder();
            for (byte b : digest) {
                signature.append(String.format("%02x", b));
            }
            return signature.toString().toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            return "";
        }
    }

    public static boolean rsaCheck(Map<String, String> params) {
        String sign = params.remove("sign");
        String compute = generateSignature(params, SECRET);

        return StringUtils.equals(sign, compute);
    }

}
